package com.vim.common.config;

import com.vim.common.exception.BusinessException;
import com.vim.common.model.exception.ExceptionEnums;
import com.vim.common.model.response.RestfulResponse;
import org.apache.shiro.authc.AuthenticationException;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * 全局异常
 */
@ControllerAdvice
public class ExceptionConfig {

    /**
     * 系统异常
     */
    @ExceptionHandler(value = RuntimeException.class)
    @ResponseBody
    public RestfulResponse RuntimeExceptionHandle(RuntimeException ex){
        ex.printStackTrace();
        return new RestfulResponse(500, "系统异常!");
    }

    /**
     * 业务异常
     */
    @ExceptionHandler(value = BusinessException.class)
    @ResponseBody
    public RestfulResponse businessExceptionHandle(BusinessException ex){
        ExceptionEnums enums = ex.getExceptionEnums();
        return new RestfulResponse(enums.getCode(), enums.getMsg());
    }

    /**
     * 权限异常
     */
    @ExceptionHandler(value = AuthenticationException.class)
    public String businessExceptionHandle(AuthenticationException ex){
        return "redirect:/views/login/index.html";
    }

    /**
     * 参数不匹配异常
     */
    @ResponseBody
    @ExceptionHandler(MissingServletRequestParameterException.class)
    public RestfulResponse messageNotReadable(MissingServletRequestParameterException ex){
        return new RestfulResponse(RestfulResponse.DEFAULT_ERROR, "缺少必要参数,参数名称为" + ex.getParameterName());
    }

}
